package cool.mtc.web.page;

import cool.mtc.core.util.StringUtil;
import cool.mtc.web.WebProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 明河
 */
@Slf4j
@RequiredArgsConstructor
public class PageHandler {
    private final WebProperties webProperties;

    public int getPage(HttpServletRequest request) {
        return this.getPageParam(request, webProperties.getPage().getPageParam(), webProperties.getPage().getDefaultPage());
    }

    public int getPageSize(HttpServletRequest request) {
        return this.getPageParam(request, webProperties.getPage().getPageSizeParam(), webProperties.getPage().getDefaultPageSize());
    }

    /**
     * 从请求中获取分页参数
     */
    private int getPageParam(HttpServletRequest request, String pageParamType, int defaultSize) {
        String pageParamStr = request.getParameter(pageParamType);
        int pageParam = defaultSize;
        if (StringUtil.isNotEmpty(pageParamStr)) {
            try {
                pageParam = Integer.parseInt(pageParamStr);
            } catch (NumberFormatException ex) {
                log.warn("分页参数{}[{}]错误，错误信息：{}", pageParamType, pageParamStr, ex.getMessage());
            }
        }
        return pageParam < 1 ? defaultSize : pageParam;
    }
}
